package cn.bjc.pet.service.impl;

import cn.bjc.basic.service.impl.BaseServiceImpl;
import cn.bjc.pet.domain.PetType;
import cn.bjc.pet.mapper.PetTypeMapper;
import cn.bjc.pet.service.IPetTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PetTypeServiceImpl extends BaseServiceImpl<PetType> implements IPetTypeService {
    
    @Autowired
    private PetTypeMapper petTypeMapper;
    
    //类型树
    @Override
    public List<PetType> typeTree() {
        //1.查询所有
        List<PetType> all = petTypeMapper.loadAll();

        //2.准备一个map
        Map<Long,PetType> map = new HashMap<>();

        //3.所有数据放入map中
        for (PetType petType : all) {
            map.put(petType.getId(), petType);

        }
        
        //4.准备一个集合保存处理之后的数据
        ArrayList<PetType> typeTree = new ArrayList<>();
        for (PetType petType : all) {
            if(petType.getPid()==null){//顶级类型
                typeTree.add(petType);
            }else {//不是顶级部门
                //获取pid
                Long pid = petType.getPid();
                //获取上级部门对象
                PetType parentPetType = map.get(pid);
                //把自己放入上级部门的children中
                parentPetType.getChildren().add(petType);
            }
        }
        //返回部门树
        return typeTree;
    }
}
